package com.example.medical.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.medical.entity.dto.*;
import com.example.medical.entity.pojo.Leadership;
import com.example.medical.service.LeadershipService;
import com.example.medical.mapper.LeadershipMapper;
import com.example.medical.utils.common.enums.Code;
import com.example.medical.utils.common.enums.Jwt;
import com.example.medical.utils.common.enums.Message;
import com.example.medical.utils.common.result.PageResponseResult;
import com.example.medical.utils.common.result.Result;
import com.example.medical.utils.config.BaseContext;
import com.example.medical.utils.config.EverythingConfig;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Date;

/**
* @author 24354
* @description 针对表【leadership】的数据库操作Service实现
* @createDate 2024-03-31 22:42:17
*/
@Service
public class LeadershipServiceImpl extends ServiceImpl<LeadershipMapper, Leadership>
    implements LeadershipService{

    @Autowired
    private LeadershipMapper leadershipMapper;
    @Autowired
    private EverythingConfig everythingConfig;

    @Override
    public Result UserGetLeadershipList(UserGetLeadershipListDto dto) {

        dto.checkParam();
        IPage<Leadership> page=new Page<>(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<Leadership> wrapper=new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(dto.getName())) {
            wrapper.like(Leadership::getLeadershipNick,dto.getName());
        }
        if (dto.getSex()!=null) {
            wrapper.like(Leadership::getLeadershipSex,dto.getSex());
        }
        page=page(page,wrapper);
        Result result=new PageResponseResult(dto.getPage(),dto.getSize(), (int) page.getTotal());
        result.setData(page.getRecords());

        return result;
    }

    @Override
    public Result LeadershipLogin(LoginDto dto) {
        if (dto==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Leadership checkLeadership = leadershipMapper.selectOne(Wrappers.<Leadership>lambdaQuery()
                .eq(Leadership::getLeadershipName, dto.getUsername()));
        if (checkLeadership==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        if (!checkLeadership.getLeadershipPassword().equals(DigestUtils.md5Hex(dto.getPassword()))) {
            return Result.errorResult(Code.LOGIN_PASSWORD_ERROR);
        }
        String id= String.valueOf(checkLeadership.getLeadershipId());
        String token = Jwts.builder()
                .setHeaderParam(Message.Jwt_Typ, Jwt.Leadership_Jwt_Key.getTyp())
                .setHeaderParam(Message.Jwt_Alg,Jwt.Leadership_Jwt_Key.getAlg())
                .setSubject(Jwt.Leadership_Jwt_Key.getName())
                .setExpiration(new Date(System.currentTimeMillis()+Jwt.Leadership_Jwt_Key.getExp()))
                .claim(Message.Leadership_id,id)
                .signWith(SignatureAlgorithm.HS256,Jwt.Leadership_Jwt_Key.getKey())
                .compact();
        return Result.okResult(token);
    }

    @Override
    public Result SaveLeadership(SaveLeadershipDto dto) {
        if (dto==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        if (!dto.getPassword().equals(dto.getPasswordCopy())) {
            return Result.errorResult(Code.PARAM_INVALID);
        }
        Leadership leadership=new Leadership();
        leadership= leadership.builder()
                .leadershipName(dto.getName())
                .password(dto.getPassword())
                .leadershipPassword(DigestUtils.md5Hex(dto.getPassword()))
                .leadershipNick(dto.getNick())
                .leadershipPhone(dto.getPhone())
                .leadershipNumber(dto.getNumber())
                .leadershipEmail(dto.getEmail()).build();
        boolean checkSave = save(leadership);
        if (!checkSave) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result UpdateLeadershipPassword(UpdatePasswordDto dto) {
        Long leadershipId = BaseContext.getCurrentId();
        Leadership checkLeadership = leadershipMapper.selectById(leadershipId);
        if (checkLeadership==null||leadershipId==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        if (dto==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        if (!checkLeadership.getPassword().equals(dto.getOldPassword())) {
            return Result.errorResult(Code.LOGIN_PASSWORD_ERROR);
        }
        Leadership leadership=new Leadership();
        leadership= leadership.builder()
                .leadershipId(checkLeadership.getLeadershipId())
                .password(dto.getNewPassword())
                .leadershipPassword(DigestUtils.md5Hex(dto.getNewPassword()))
                .build();
        boolean checkSave = updateById(leadership);
        if (!checkSave) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result UpdateLeadershipDetail(MultipartFile file, Integer sex) throws Exception {

        Long leadershipId = BaseContext.getCurrentId();
        Leadership checkLeadership = leadershipMapper.selectById(leadershipId);
        if (checkLeadership==null||leadershipId==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        String url = everythingConfig.Upload(file);
        Leadership leadership=new Leadership();
        leadership= leadership.builder()
                .leadershipId(checkLeadership.getLeadershipId())
                .leadershipImgUrl(url)
                .leadershipSex(sex).build();
        boolean checkUpdate = updateById(leadership);
        if (!checkUpdate) {
            return Result.errorResult(Code.SERVER_ERROR);
        }

        return Result.okResult(Code.SUCCESS);
    }


    @Override
    public Result AdminRemoveLeadershipArr(String[] ids) {
        if (BaseContext.getCurrentId()==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        for (String id:ids) {
            Leadership checkLeadership = leadershipMapper.selectById(id);
            if (checkLeadership==null) {
                return Result.errorResult(Code.DATA_NOT_EXIST);
            }
            boolean checkRemove = removeById(id);
            if (!checkRemove) {
                return Result.errorResult(Code.SERVER_ERROR);
            }
        }
        return Result.okResult(Code.SUCCESS);
    }
    @Override
    public Result AdminUpdateLeadership(Long id,String name, String nick, Long phone, Long number, MultipartFile file, Integer sex, String email) throws Exception {
        if (BaseContext.getCurrentId()==null){
            return Result.errorResult(Code.NEED_LOGIN);
        }
        Leadership checkLeadership = leadershipMapper.selectById(id);
        if (checkLeadership==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        if (StringUtils.isNotBlank(name)) {
            checkLeadership.setLeadershipName(name);
        }
        if (StringUtils.isNotBlank(nick)) {
            checkLeadership.setLeadershipNick(nick);
        }
        if (phone!=null) {
            checkLeadership.setLeadershipPhone(phone);
        }
        if (number!=null) {
            checkLeadership.setLeadershipNumber(number);
        }
        if (file!=null && file.getSize() > 0) {
            String upload = everythingConfig.Upload(file);
            checkLeadership.setLeadershipImgUrl(upload);
        }
        if (StringUtils.isNotBlank(email)) {
            checkLeadership.setLeadershipEmail(email);
        }
        boolean checkUpdate = updateById(checkLeadership);
        if (!checkUpdate) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        return Result.okResult(Code.SUCCESS);
    }


    @Override
    public Result AdminSaveLeadership(String name, String nick, Long phone, Long number, MultipartFile file, Integer sex, String email) throws Exception {
        if (BaseContext.getCurrentId()==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        String upload = everythingConfig.Upload(file);
        Leadership leadership=new Leadership().builder()
                .leadershipName(name)
                .leadershipNick(nick)
                .leadershipPhone(phone)
                .leadershipNumber(number)
                .leadershipImgUrl(upload)
                .leadershipSex(sex)
                .leadershipEmail(email)
                .password("123456")
                .leadershipPassword(DigestUtils.md5Hex("123456"))
                .saveTime(String.valueOf(LocalDateTime.now())).build();
        boolean checkSave = save(leadership);
        if (!checkSave) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result AdminUpdateLeadershipPassword(Long id) {
        if (BaseContext.getCurrentId()==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        Leadership checkLeadership = getById(id);
        if (checkLeadership==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        checkLeadership.setPassword("123456");
        checkLeadership.setLeadershipPassword(DigestUtils.md5Hex("123456"));
        boolean checkUpdate = updateById(checkLeadership);
        if (!checkUpdate) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        return Result.okResult(Code.SUCCESS);
    }

}




